package com.qc.common;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class Util {

	private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	/*
	 * Converts a byte array to hex string
	 */
	protected static String toHexString(byte[] block) {
		StringBuffer buf = new StringBuffer();
		int len = block.length;

		for (int i = 0; i < len; i++) {
			int high = ((block[i] & 0xf0) >> 4);
			int low = (block[i] & 0x0f);
			buf.append(hexChars[high]);
			buf.append(hexChars[low]);
			// if (i < len-1) {
			// buf.append(":");
			// }
		}
		return buf.toString();
	}
	
	/**
	 * 生成6位数字的随机数字，用于手机号验证
	 *
	 * @return
	 */
	public static int get6code() {
		Random rnd = new Random();
		int n = 100000 + rnd.nextInt(900000);
		return n;
	}
	
	/**
	 * 随机生成8位随机数字，用于默认的用户昵称
	 */
	public static int get8Code() {
		Random rnd = new Random();
		int n = 10000000 + rnd.nextInt(90000000);
		return n;
	}
	
	private static Logger dailyLog = Logger.getLogger("");
	private static Logger exceptionLog = Logger.getLogger("exception");
	private static Logger smsYtLog = Logger.getLogger("smsYt");

	public static void logExceptionINFO(Object s) {
		exceptionLog.info(s);
	}
	
	public static void logYXDebug(Object s) {
		smsYtLog.debug(s);
	}
	
	public static void logYXInfo(Object s) {
		smsYtLog.info(s);
	}
	
	public static void logDailyDebug(Object s) {
		dailyLog.debug(s);
	}
	
	public static void logDailyInfo(Object s) {
		dailyLog.info(s);
	}
	
	/**
	 * 创建支付随机字符串 (微信支付需要用到)
	 * @return
	 */
	public static String getNonceStr(){
		return RandomUtil.randomString(RandomUtil.LETTER_NUMBER_CHAR, 32);
	}
	
	/**
	 * 返回客户端ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getRemoteAddrIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}
}
